from contextlib import contextmanager

@contextmanager
def managed_file(name):
    try:
        f = open(name, 'w')
        yield f
    finally:
        f.close()

# Usage:
with managed_file('hello.txt') as f:
    f.write('hello, world!')

print('''
用contextmanager装饰器和yield语句，

创建了一个上下文管理器，
确保文件在操作完成后被正确关闭。

''')